package com.guapi.schedule;

import cn.hutool.core.collection.CollectionUtil;
import com.guapi.dao.SystemJob;
import com.guapi.service.JobService;
import com.guapi.thread.ScheduleThread;
import com.guapi.util.BaseConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

@Component
public class InitTask implements CommandLineRunner {
    @Autowired
    private CronTaskRegister cronTaskRegister;
    @Autowired
    private JobService jobService;

    @Override
    public void run(String... args) throws Exception {
        //获取所有需要执行的定时任务
        SystemJob systemJob = new SystemJob();
        systemJob.setEnable(BaseConstant.ISENABLE);
        List<SystemJob> list = jobService.getByConditions(systemJob);
        if (CollectionUtil.isNotEmpty(list)) {
            list = list.stream().filter(SystemJob::judgeIsEnable).collect(Collectors.toList());
        }
        for (SystemJob job : list) {
            System.out.println(job.getCronExpression());
            ScheduleThread scheduleThread = new ScheduleThread(job.getBeanName(), job.getMethodName(), job.getMethodParams());
            cronTaskRegister.addCronTask(scheduleThread, job.getCronExpression());

        }
    }
}
